
var _ = require('lodash'),
    Q = require('q'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    bizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller');

exports.getProductFlow = function(req, res) {
    var parameter = req.body.Parameter,
        barcode = parameter.Barcode;

    var productFlow = {};
    queryBaseInfo(barcode).then(function (basicInfo) {
        productFlow.basicInfo = basicInfo;
        return queryBizRecords(basicInfo.barcodeMasterId);
    }).then(function (bizRecords) {
        _.merge(productFlow, bizRecords);
        res.json({
            Data: productFlow,
            Error: null
        });
    }).catch(function (err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
};

function queryBaseInfo (barcode) {
    var deferred = Q.defer();

    barcodeMasterController.findBarcodeMaster(barcode, function (err, barcodeMaster) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (!barcodeMaster || barcodeMaster.BarcodeType != 0) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询物料错误';
            newErr.message = '无法识别的芯片，请重新扫描！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve({
            barcodeMasterId: barcodeMaster._id,
            ItemMasterCode: barcodeMaster.ItemMasterCode,
            OperationName: barcodeMaster.OperationName,
            QCStatus: barcodeMaster.QCStatus,
            ItemMasterName: barcodeMaster.ItemMaster.ItemMasterName,
            Specification: barcodeMaster.ItemMaster.Specification,
            ItemCategory: barcodeMaster.ItemMaster.ItemCategory,
            MOCode: barcodeMaster.MO.Code,
            Customer: barcodeMaster.MO.Customer,
            StartDateTime: barcodeMaster.MO.StartDateTime,
            EndDateTime: barcodeMaster.MO.EndDateTime,
            MOLotNumber: barcodeMaster.MOLotNumber,
            ShipLotNumber: barcodeMaster.ShipLotNumber
        });
    });

    return deferred.promise;
}

function queryBizRecords (barcodeMasterId) {
    var deferred = Q.defer();

    bizRecordController.findByBarcodeMaster(barcodeMasterId, function (err, bizRecords) {
        if (err) {
            deferred.reject(err);
            return;
        }
        var results = {
            bizCatalog: [],
            bizRecords: {}
        };
        var depUniqueId = 1000,
            lastResultRecord = {},
            tmpRecord, lastCatalogId, lastWork, lastBizCollectTime;
        for (var i = 0, len = bizRecords.length; i < len; i++) {
            tmpRecord = bizRecords[i];
            if (tmpRecord.WorkLocation.Department._id !== lastCatalogId) {
                results.bizCatalog.push({
                    UniqueId: depUniqueId,
                    Code: tmpRecord.WorkLocation.Department.Code,
                    Name: tmpRecord.WorkLocation.Department.Name
                });
                results.bizRecords[depUniqueId] = [];

                lastCatalogId = tmpRecord.WorkLocation.Department._id;
                depUniqueId++;
            }
            if (tmpRecord.Work.toString() === lastWork) {
                lastResultRecord.WorkTime = ((tmpRecord.CollectDateTime - lastBizCollectTime) / 60000).toFixed(2);
            } else {
                lastResultRecord = {
                    CollectDateTime: tmpRecord.CollectDateTime,
                    TerminalName: tmpRecord.TerminalName,
                    WorkName: tmpRecord.WorkName,
                    Users: tmpRecord.Users
                };
                if (tmpRecord.QCType) {
                    lastResultRecord.QCStatus = tmpRecord.QCStatus;
                }
                lastResultRecord.QCFlag = tmpRecord.QCType ? true : false;
                results.bizRecords[depUniqueId - 1].push(lastResultRecord);
            }
            lastWork = tmpRecord.Work.toString();
            lastBizCollectTime = tmpRecord.CollectDateTime;
        }
        deferred.resolve(results);
    });

    return deferred.promise;
}